import {
    Component, OnInit, Output, Input, EventEmitter, ViewChild, TemplateRef, HostBinding, NgZone, Injector
} from '@angular/core';
import { NotifyService } from '@farris/ui-notify';
import { FormBasicService, DesignerEnvType, SchemaService, FormSchemaEntity, FormSchemaEntityField } from '@farris/designer-services';
import { TreeNode, TreeTableComponent } from '@farris/ui-treetable';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { FarrisMetadataDto } from '@farris/designer-services';


@Component({
    selector: 'app-place-field-selector',
    templateUrl: './place-field-selector.component.html'
})
export class PlaceFieldSelectorComponent implements OnInit {
    @Output() closeModal = new EventEmitter<any>();
    @Output() submitModal = new EventEmitter<any>();
    @Input() value;
    @Input() editorParams = { voId: null, formId: null };

    @ViewChild('modalFooter') modalFooter: TemplateRef<any>;
    modalConfig = {
        title: '字段选择器',
        width: 1000,
        height: 700,
        showButtons: true,
        showMaxButton: true
    };
    fieldsTreeData: TreeNode[];

    // 树表列配置
    treeCols = [{ field: 'name', title: '名称' }, { field: 'label', title: '编号' }, { field: 'bindingPath', title: '绑定字段' }];

    // 树表实例
    @ViewChild('treeTable') treeTable: TreeTableComponent;

    @HostBinding('class')
    class = 'd-flex f-utils-fill-flex-column h-100 px-3';

    /** 零代码元数据接口 */
    private loadMetaDataURL = '/api/dev/nocode/v1.0/micro-apps/metadatas';

    /** 请求服务 */
    private http: HttpClient;
    private headerOptions = {
        headers: new HttpHeaders({
            'Content-Type': 'application/json'
        })
    };

    constructor(
        private formBasicServ: FormBasicService,
        private notifyService: NotifyService,
        private injector: Injector,
        private schemaServ: SchemaService,
        private ngZone: NgZone) {
        this.http = this.injector.get(HttpClient);

    }

    ngOnInit(): void {
        switch (this.formBasicServ.envType) {
            case DesignerEnvType.designer: {
                this.getSchemaFieldsFromVo();
                break;
            }
            case DesignerEnvType.noCode: {
                this.getSchemaFieldsFromForm();
                break;
            }
            default: {
                this.notifyService.warning('暂不支持。');
            }
        }

    }

    /**
     * 低代码：根据地点VO元数据id，获取VO对应的schema字段列表
     */
    private getSchemaFieldsFromVo() {
        if (!this.editorParams.voId) {
            return;
        }

        const sessionId = '';
        this.schemaServ.converVO2Schema(this.editorParams.voId, sessionId).subscribe(data => {
            if (data) {
                const mainEntity = data.entities[0] as FormSchemaEntity;
                this.assembleFieldsToTree(mainEntity.type.fields);
            }
        }, () => {
            this.notifyService.error('获取视图对象元数据失败');
        });
    }
    /**
     * 零代码：根据地点表单form元数据id,获取表单中记录的voId，然后根据voId获取vo对应的schema字段列表
     */
    private getSchemaFieldsFromForm() {

        this.http.get(`${this.loadMetaDataURL}/${this.editorParams.formId}`, this.headerOptions).subscribe((data: FarrisMetadataDto) => {
            if (data && data.content) {
                let domJson;
                if ('' + data.content === data.content) {
                    domJson = JSON.parse(data.content);
                } else {
                    domJson = data.content;
                }
                const schema = domJson.Contents.module.schemas[0];
                const voId = schema.id;

                this.schemaServ.convertVoToSchemaForNoCodeForm(voId).subscribe(newSchema => {
                    const mainEntity = newSchema.entities[0] as FormSchemaEntity;
                    this.assembleFieldsToTree(mainEntity.type.fields);
                }, () => {
                    this.notifyService.error('获取视图对象元数据失败');
                });

            }
        }, () => {
            this.notifyService.error('获取表单元数据失败');
        });
    }
    /**
     * schema字段集合组装成树
     * @param fields schema字段集合
     */
    private assembleFields2Tree(fields: FormSchemaEntityField[]) {
        const treeData = [];
        fields.forEach(element => {
            // 关联表字段 / UDT字段
            let children = [];
            if (element.type && element.type.fields && element.type.fields.length > 0) {
                children = this.assembleFields2Tree(element.type.fields);

            }

            treeData.push({
                data: element,
                children,
                expanded: true,
                selectable: children.length > 0 ? false : true
            });
        });
        return treeData;
    }

    private assembleFieldsToTree(mainFields: FormSchemaEntityField[]) {

        this.fieldsTreeData = this.assembleFields2Tree(mainFields);

        // 默认选中行
        this.ngZone.runOutsideAngular(() => {
            setTimeout(() => {
                if (!this.value) { return; }
                try {
                    this.treeTable.selectNode(this.value);
                } catch (e) {
                    this.treeTable.clearSelections();
                }
            });
        });
    }
    clickConfirm() {
        if (!this.treeTable.selectedRow) {
            this.notifyService.warning('请选择字段');
            return;
        }

        const selectedData = this.treeTable.selectedRow.data;

        this.submitModal.emit({ value: selectedData.bindingPath });
    }

    clickCancel() {

        this.closeModal.emit();
    }
}
